// -------------------------------------------------------------------------请求的封装
const storage = require('./storage')
const config = require("./config")
const hyphenate = require("./hyphenate")
let isLoginAsk = false
// 请求封装
function request(url, method, data, transform, header = {}) {
  return new Promise((resolve, reject) => {
    let header = {
      'content-type': 'application/json' // 默认值
    }
    // token存到header中
    const token = storage.getToken()
    if (token) {
      header.token = `${token}`
    }
    wx.request({
      url: config.host + url,
      method: method,
      data: transform ? JSON.parse(hyphenate.toKebabCaseJSON(JSON.stringify(data))) : data,
      header: header,
      success: async function (res) {
        const data = res.data
        wx.hideLoading()
        if (data.errcode == 401) {
          if (isLoginAsk) {
            // wx.showModal({
            //   title: "注意",
            //   content:
            //     "已经重新登录仍异常，请点击确定重试",
            //   showCancel: false,
            //   success: async (res) => {
            //     isLoginAsk = false
            //     await applogin()
            //     res = await request(url, method, data, transform)
            //     resolve(res)
            //   }
            // });
            return
          }
          isLoginAsk = true
          await applogin()
          res = await request(url, method, data, transform)
          resolve(res)
          return
        } else if (res.statusCode != 200) {
          // 其他非正常情况
          if (res.data && res.data.msg) {
            const errmsg = res.data.msg == "fail" ? res.data.data : res.data.msg
            wx.showModal({
              title: "错误",
              content: errmsg,
              showCancel: false
            });
            reject(res.data.code)
            return
          } else {
            const errmsg = "服务器异常 错误码:" + res.statusCode
            wx.showModal({
              title: "错误",
              content: errmsg,
              showCancel: false,
              success(res) { }
            });
            reject(502)
            return
          }
        }

        resolve(transform ? JSON.parse(hyphenate.toCamelCaseJSON(JSON.stringify(res.data))) : res.data)
      }
    })
  })
}
// 初始化
async function handleLoginCode(res) {
  let response;
  try {
    response = await post('/user/login', { code: res.code });

  } catch (error) {
    wx.showModal({
      title: "错误",
      content: error,
      showCancel: false,
      confirmText: "不再提醒",
      success(res) { }
    });
    console.log("error", error)
    return;
  }
  // console.log("response", response)
  const data = response.data;

  // 存储token
  storage.saveToken(data.token);
  storage.saveTokenExpire(data.expire);
  getApp().globalData.user = data
}
async function wxLogin() {
  return new Promise(resolve => {
    wx.login({
      success: res => resolve(res)
    });
  });
}
async function applogin() {
  wx.showLoading({ title: "正在登录中" })
  const res = await wxLogin();
  await handleLoginCode(res);
}


function get(url, data, transform) {
  return request(url, 'GET', data, transform)
}
function post(url, data, transform) {
  return request(url, 'POST', data, transform)
}

module.exports = {
  get,
  post
}
// -------------------------------------------------------------------------请求的封装
